package com.jiuli_travel.blog_service.job.once;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.jiuli_travel.blog_service.model.entity.Blog;
import com.jiuli_travel.blog_service.model.es.BlogEsDTO;
import com.jiuli_travel.blog_service.service.IBlogService;
import jakarta.annotation.PostConstruct;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;

@Component
public class InitExportBlogDataToEs {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private IBlogService blogService;

//    @PostConstruct // bean创建完成后执行
    public void doExport() throws IOException {
        // 1. 获取数据库中blog的所有数据
        List<Blog> blogList = blogService.list();

        // 2. 转化数据格式
        List<BlogEsDTO> blogEsDTOS = BeanUtil.copyToList(blogList, BlogEsDTO.class);


        // 3. 导入到es中
        // 3.1 准备请求
        BulkRequest bulkRequest = new BulkRequest();
        // 3.2 准备DSL
        blogEsDTOS
                .forEach(blogEsDTO -> {
                    IndexRequest indexRequest = new IndexRequest("blog_es").id(blogEsDTO.getId().toString());
                    indexRequest.source(JSONUtil.toJsonStr(blogEsDTO), XContentType.JSON);
                    bulkRequest.add(indexRequest);
                });
        // 3.3 发起请求
        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);

        System.out.println("牛皮丫只能说");
    }

}















